package com.windaka.elements.utils;


import com.windaka.elements.model.dto.BaseDTO;

import java.io.Serializable;
import java.util.List;


/**
 * <p><strong>返回结果的打包工具</strong></p>
 * <li>
 * <p>
 *     <strong>示例1: es打包分页结果</strong> <br>
 *     return PageResultUtils.esResult(dto, total, dataList);
 * </p>
 * </li>
 * @author song
 *
 * @since 10:02 2021/7/31
 **/

public class PageResultUtils {

    private PageResultUtils() {}

    /**
     * ElasticSearch 到 1万条往后 效率会变慢
     */
    private static final Integer ES_MAX_DATA_SIZE = 10000;

    /**
     * <p>
     *     <strong>示例1: es打包分页结果</strong> <br>
     *     return PageResultUtils.esResult(dto, total, dataList);
     * </p>
     * @author song
     * @param baseDTO 包含 page、limit
     * @param totalCount 查询的总数
     * @param dataList 返回的数据
     * @return HashMap
     * @since 2021/5/30
     */
    public static <T extends Serializable> RetPage<T> esResult(BaseDTO baseDTO, Long totalCount, List<T> dataList) {
        RetPage<T> retPage = RetPage.result(dataList);
        // PageParamUtils里 checkEsPage对当前页数-1了
        int page = baseDTO.getPage();
        int nowPage = page + 1;
        int limit = baseDTO.getLimit();
        retPage.setPage(nowPage);
        retPage.setLimit(limit);
        if (nowPage > 1) {
            retPage.setPrePage(nowPage - 1);
        } else {
            retPage.setPrePage(1);
        }
        if ((long) page * limit > totalCount || page * limit > ES_MAX_DATA_SIZE) {
            retPage.setNextPage(nowPage);
        } else {
            retPage.setNextPage(page + 1);
        }
        retPage.setTotal(totalCount);
        return retPage;
    }

}
